//
//  HMLocaltionManager.m
//  localLife
//
//  Created by Limonwei on 15/11/23.
//  Copyright © 2015年 heima. All rights reserved.
//

#import "HMLocaltionManager.h"
#import <CoreLocation/CoreLocation.h>

@interface HMLocaltionManager ()<CLLocationManagerDelegate>

@property(nonatomic,strong)CLLocationManager *manager;

@property(nonatomic,copy)successLocal successLocal;

@property(nonatomic,copy)errorLocal errorLocal;

@property(nonatomic,assign)BOOL local;

@end

@implementation HMLocaltionManager

-(instancetype)init{
    
    if (self = [super init]) {
        _manager = [[CLLocationManager alloc]init];
        
        if ([_manager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
            [_manager requestAlwaysAuthorization];
        }
        _manager.delegate = self;
    }
    return self;
    
}

+(id)shareInstance{
    
    static id manager = nil;
    
    static dispatch_once_t onceToken;
    
    dispatch_once(&onceToken, ^{
        
        manager = [[self alloc]init];
    });
    return manager;
    
}

-(void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray<CLLocation *> *)locations{
    
    [_manager stopUpdatingLocation];
    
    if (locations.count>0) {
        CLLocation *location = locations.lastObject;
        
        if (!_local) {
            self.successLocal(location.coordinate);
            _local = YES;
        }
    }
    
}

-(void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status{
    
    if (status == kCLAuthorizationStatusDenied) {
        [_manager stopUpdatingLocation];
    }
}


-(void)localSuccess:(successLocal)success withError:(errorLocal)error{
    
    [_manager startUpdatingLocation];
    
    _local = NO;
    
    self.successLocal = success;
    
    
}


+(void)localSuccess:(successLocal)success withError:(errorLocal)error{
    
    
    [[self shareInstance]localSuccess:success withError:error];
    
}

@end

































